

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="caoyusang">
  <meta name="keywords" content="">
  <title>Java内存区域 - caoyusang的科研日常</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>caoyusang</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/7.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-05-28 19:38" pubdate>
        2021年5月28日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      17
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">Java内存区域</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：22 分钟前
                
              </p>
            
            <div class="markdown-body" id="post-body">
              <h2 id="Java内存区域"><a href="#Java内存区域" class="headerlink" title="Java内存区域"></a>Java内存区域</h2><h3 id="1-Java内存区域划分"><a href="#1-Java内存区域划分" class="headerlink" title="1.Java内存区域划分"></a>1.Java内存区域划分</h3><p>JVM在执行Java程序的过程中会把它管理的内存区域划分成两类用途不同的数据区：</p>
<ul>
<li><p>线程共有（线程共享）区域——堆和方法区</p>
</li>
<li><p>线程私有（线程隔离）区域——程序计数器、虚拟机栈和本地方法栈</p>
</li>
</ul>
<img src="/2021/05/28/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/image-20210526164944774.png" srcset="/img/loading.gif" class="">
<h3 id="2-线程共享数据区"><a href="#2-线程共享数据区" class="headerlink" title="2.线程共享数据区"></a>2.线程共享数据区</h3><h4 id="堆"><a href="#堆" class="headerlink" title="堆"></a><code>堆</code></h4><img src="/2021/05/28/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/image-20210526185840704.png" srcset="/img/loading.gif" class="">
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">用途</th>
<th style="text-align:center"><code>完成几乎所有Java实例对象的内存分配，进行垃圾回收的主要内存区域</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><strong>划分</strong></td>
<td style="text-align:center">年轻代<code>8 : 1 : 1(Eden区 : From Survivor 0 : To Survivor 1 区)</code>、老年代</td>
</tr>
<tr>
<td style="text-align:center"><strong>内存空间大小</strong></td>
<td style="text-align:center"><strong>大</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>垃圾回收模式</strong></td>
<td style="text-align:center"><strong>以主流的HotSpot为例，采用<code>分代回收</code>策略，对于年轻代的对象采取复制算法，对老年代采取标记-清除或者标记-整理算法</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>异常情况</strong></td>
<td style="text-align:center"><strong>堆中没完成实例分配，且堆此时无法再扩展，JVM会抛出<code>OOM</code>异常</strong></td>
</tr>
</tbody>
</table>
</div>
<h5 id="对象分配策略"><a href="#对象分配策略" class="headerlink" title="对象分配策略"></a>对象分配策略</h5><p>当有对象需要分配时，一个对象永远<code>优先被分配在年轻代的 Eden 区</code>，等到 Eden 区域内存不够时，Java 虚拟机会启动垃圾回收。此时 Eden 区中没有被引用的对象的内存就会被回收，在一次新生代垃圾回收后，Eden区中所有存活的对象都会被<code>复制</code>到To Survivor区，而在From Survivor区中，<code>仍存活的对象会根据它们的年龄值决定去向</code>，年龄值达到<code>年龄阀值</code>（默认为15，新生代中的对象每熬过一轮垃圾回收，年龄值就加1，GC分代年龄存储在对象的header中）的对象会被移到老年代中，没有达到阀值的对象会被复制到To Survivor区。接着清空Eden区和From Survivor区，新生代中存活的对象都在To Survivor区。接着， <code>From Survivor区和To Survivor区会交换它们的角色</code>，也就是新的To Survivor区就是上次GC清空的From Survivor区，新的From Survivor区就是上次GC的To Survivor区，总之，不管怎样都会保证To Survivor区在一轮GC后是空的。GC时当To Survivor区没有足够的空间存放上一次新生代收集下来的存活对象时，需要依赖老年代进行分配担保，将这些对象存放在老年代中。</p>
<h4 id="方法区"><a href="#方法区" class="headerlink" title="方法区"></a><code>方法区</code></h4><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">用途</th>
<th style="text-align:center">存储已被虚拟机加载的<code>类的结构信息(字段和方法数据、构造方法)、常量、静态变量</code>、即时编译器编译后的代码缓存等数据，像是堆的一个逻辑部分</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><strong>异常情况</strong></td>
<td style="text-align:center"><strong>方法区无法满足新的内存分配需求时，抛出OOM异常</strong></td>
</tr>
</tbody>
</table>
</div>
<h3 id="3-线程私有数据区"><a href="#3-线程私有数据区" class="headerlink" title="3.线程私有数据区"></a>3.线程私有数据区</h3><h4 id="程序计数器"><a href="#程序计数器" class="headerlink" title="程序计数器"></a><code>程序计数器</code></h4><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">用途</th>
<th style="text-align:center">指示当前线程所<code>执行的字节码的行号指示器</code>。字节码解释器工作时就是通过改变程序计数器的值来选取下一条需要执行的字节码指令，程序控制中的<code>分支、循环、跳转、异常处理、线程恢复</code>等都依赖程序计数器</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><strong>私有性质</strong></td>
<td style="text-align:center"><strong>JVM多线程通过线程切换并分配CPU时间实现的，任一确定的时刻，一个CPU指挥执行一条线程中的指令。所以为了线程切换后能恢复到正确的执行位置，每个线程都需要一个独立的程序计数器。</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>内存空间大小</strong></td>
<td style="text-align:center"><strong>小</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>生命周期</strong></td>
<td style="text-align:center"><strong>随着线程的创建而创建，随着线程的消亡而消亡</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>真实值</strong></td>
<td style="text-align:center"><strong>如果执行的是<code>Java方法</code>，那么计数器记录的就是<code>正在执行的JVM字节码指令的地址</code>；如果执行的是<code>本地(Native)方法</code>，那么计数器的值则应该为空(<code>Undefined</code>)</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>异常情况</strong></td>
<td style="text-align:center"><strong>唯一一个不会出现 <code>OutOfMemoryError(OOM)</code> 的内存区域</strong></td>
</tr>
</tbody>
</table>
</div>
<h4 id="虚拟机栈"><a href="#虚拟机栈" class="headerlink" title="虚拟机栈"></a><code>虚拟机栈</code></h4><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">含义</th>
<th style="text-align:center">描述<code>Java方法执行的线程内存模型</code>，每个Java方法被执行时，虚拟机都会同步创建一个栈帧</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><strong>组成</strong></td>
<td style="text-align:center"><strong>Java虚拟机栈由一个个<code>栈帧</code>组成</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>栈帧</strong></td>
<td style="text-align:center"><strong>存储了<code>局部变量表</code>、操作数栈、动态链接、方法出口等信息</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>局部变量表</strong></td>
<td style="text-align:center"><strong>主要存放了编译期可知的各种<code>基本数据类型</code>（boolean、byte、char、short、int、float、long、double）、<code>对象引用</code>（reference 类型，它不同于对象本身，可能是一个指向对象起始地址的引用指针，也可能是指向一个代表对象的句柄或其他与此对象相关的位置）和returnAddress类型(指向了一条字节码指令的地址)。</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>生命周期</strong></td>
<td style="text-align:center"><strong>和线程相同</strong></td>
</tr>
<tr>
<td style="text-align:center"><strong>异常情况</strong></td>
<td style="text-align:center"><strong>如果线程请求的栈深度大于虚拟机允许的最大深度，就会抛出<code>StackOverflowError</code>异常(栈溢出异常)；如果虚拟机在动态扩展栈时无法申请到足够的内存空间，则抛出<code>OutOfMemoryError</code>异常</strong></td>
</tr>
</tbody>
</table>
</div>
<h4 id="本地方法栈"><a href="#本地方法栈" class="headerlink" title="本地方法栈"></a><code>本地方法栈</code></h4><p>为虚拟机使用到的本地方法服务。和Java虚拟机栈发挥的作用非常相似，和虚拟机栈一样，本地方法栈也会在栈深度溢出或者栈动态扩展失败时分别抛出<code>StackOverflowError</code>异常和<code>OutOfMemoryError</code>异常。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Java/">Java</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/JVM/">JVM</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/05/28/%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">类加载机制</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/05/28/%E7%BC%96%E8%AF%91JDK/">
                        <span class="hidden-mobile">编译JDK</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Java内存区域&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  











</body>
</html>
